package com.example.demomk.Utils;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.demomk.Adapter.PrintDetailsAdapter;
import com.example.demomk.Interface.OnDialogButtonClickListener;
import com.example.demomk.ViewModel.MeasurementViewModel;
import com.example.demomk.databinding.DialogCustomBinding;
import com.example.demomk.databinding.DialogPrintBinding;
import com.example.demomk.entity.AvgMeasurementWithDetails;
import com.example.demomk.entity.MeasurementSummary;

import java.util.ArrayList;
import java.util.List;

public class Dialogprint extends Dialog {
    private OnDialogButtonClickListener listener;
    private  DialogPrintBinding binding;
    private int start,end;
    private MeasurementViewModel  viewModel;
    private final FragmentActivity fragmentActivity;
    private PrintDetailsAdapter adapter;
    private RecyclerView recyclerView;
    private EditText title;

    private List<Integer> selectedIds;

    public Dialogprint(@NonNull Context context, @Nullable OnDialogButtonClickListener listener, List<Integer> selectedIds,@NonNull FragmentActivity activity) {
        super(context);
        this.listener = listener;
        this.selectedIds = selectedIds;
        this.fragmentActivity = activity;
        initView();
    }
    //这个构造函数和 定义的final类型的FragmentActivty有冲突
//    public Dialogprint(@NonNull Context context, int themeResId) {
//        super(context, themeResId);
//    }

    @Deprecated
    public Dialogprint(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        throw new UnsupportedOperationException("请使用带 FragmentActivity 的构造函数");
    }
    public Dialogprint(@NonNull Context context, @Nullable OnDialogButtonClickListener listener,@NonNull FragmentActivity activity) {
        super(context);
        this.listener = listener;
        this.fragmentActivity = activity;

    }

    private void initView() {
        // 设置自定义布局
        binding = DialogPrintBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        title = binding.etTitle;

        viewModel = new ViewModelProvider(fragmentActivity).get(MeasurementViewModel.class);
        recyclerView = binding.printRecyclerView;
        adapter = new PrintDetailsAdapter();
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));


        // 使用 LiveData 监听数据变化
        viewModel.summaryList.observe(fragmentActivity, summaries -> {
            if (summaries != null && !summaries.isEmpty()) {
                List<MeasurementSummary> sortedList = new ArrayList<>(summaries);
                sortedList.sort((o1, o2) -> Integer.compare(o1.getAvg_id(),o2.getAvg_id()));
                adapter.setDataList(sortedList);
            }
        });


        viewModel.loadSummaries(selectedIds);

        binding.btnConfirm.setOnClickListener(v -> {
            String titles = title.getText().toString().trim();
            if (!TextUtils.isEmpty(titles)) {
                // 非空，执行操作
                dismiss();
            } else {
                Toast.makeText(fragmentActivity, "报告标题不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            StdDialogData data = new StdDialogData();
            // 确认按钮点击事件
            if (listener != null) {
                listener.onCancel(start, end,titles,data);
            }
        });

        // 设置点击外部可取消
        setCancelable(true);//用户点击返回键时
        setCanceledOnTouchOutside(false);//点击对话框外部区域

        // 设置窗口属性
        Window window = getWindow();
        if (window != null) {
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

            // 关键修改：添加以下标志
            // 获取屏幕宽度
            DisplayMetrics metrics = new DisplayMetrics();
            window.getWindowManager().getDefaultDisplay().getMetrics(metrics);
            int screenWidth = metrics.widthPixels;

            //修改屏幕高度
            int screenHeight = metrics.heightPixels;

            // 设置对话框宽度为屏幕宽度的90%
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = (int) (screenWidth * 0.9);
//            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            params.height = (int) (screenHeight * 0.85);
            params.dimAmount = 0.2f;
            window.setAttributes(params);
        }

        //点击关闭按钮
        binding.ivClose.setOnClickListener(v -> {
            dismiss();
        });
    }

}
